package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备表Service业务层处理
 *
 * @author 陈舜涛
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     *
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncPorductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {

        String products = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(products)) {
            return Collections.emptyList();
        }
        //解析数据并返回
        return JSONUtil.toList(products, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {
        //1.设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //2.设备标识是否重复
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count > 0) {
            throw new BaseException("设备标识重复");
        }
        //3.同一位置是否绑定了相同的产品
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getLocationType() != null, Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()));
        if (count > 0) {
            throw new BaseException("同一位置已绑定相同产品");
        }
        //4.注册设备上传到iot平台
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(deviceDto.getNodeId());
        body.setDeviceName(deviceDto.getDeviceName());
        body.setProductId(deviceDto.getProductKey());
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("设备注册失败");
        }
        //5。在本地保存设备信息
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation()));
        save(device);
    }

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1.查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        //2.调用api接口去iot平台获取数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备详情失败");
        }
        String status = response.getStatus();
        String activeTimeStr = response.getActiveTime();

        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        detailVo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        detailVo.setDeviceStatus(status);
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            // 日期时区转换
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            detailVo.setActiveTime(DateTimeZoneConverter.utcToShanghai(activeTime));
        }

        return detailVo;
    }

    /**
     * 查询设备服务属性
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备详情失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (shadow.isEmpty()) {
            return Collections.emptyList();
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        String eventTimeStr = reported.getEventTime();
        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        LocalDateTime localDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        //转换时区
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(localDateTime);

        List<Map<String, Object>> list = new ArrayList<>();
        properties.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 修改设备
     *
     * @param device
     */
    @Transactional
    @Override
    public void edit(Device device) {
        //修改iot设备名称
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(device.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse updateDeviceResponse = client.updateDevice(request);
        if (updateDeviceResponse.getHttpStatusCode() != 200) {
            throw new BaseException("修改设备失败");
        }
        //修改数据库
        updateById(device);
//        Long count = count(Wrappers.<Device>lambdaQuery()
//
//                .eq(Device::getBindingLocation, device.getBindingLocation())
//                .eq(Device::getProductKey, device.getProductKey())
//                .eq(Device::getLocationType, device.getLocationType())
//                .eq(device.getLocationType() != null, Device::getPhysicalLocationType, device.getPhysicalLocationType()));
//        if (count > 0) {
//            throw new BaseException("同一位置已绑定相同产品");
//        }
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(request);
        if (deleteDeviceResponse.getHttpStatusCode() != 204) {
            throw new BaseException("删除设备失败");
        }
        remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse showProductResponse = client.showProduct(request);
        if (showProductResponse.getHttpStatusCode() != 200) {
            throw new BaseException("查询产品失败");
        }
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        if (ObjectUtil.isEmpty(serviceCapabilities)) {
            return Collections.emptyList();
        }
        return serviceCapabilities;
    }
}
